package com.example.txjc;

import android.content.Context;
import android.content.Intent;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.widget.Button;
import android.widget.Toast;

import com.example.txjc.Activity.ImagecontrastActivity;
import com.example.txjc.Activity.TakePhotoActivity;
import com.example.txjc.Activity.TakeVideoActivity;
import com.example.txjc.Activity.VideoActivity;
import com.example.txjc.Model.PhotoRequest;
import com.example.txjc.Util.NetUtil;
import com.example.txjc.Util.ProjectConfig;
//import com.example.txjc.Util.SerialPortUtils;
import com.example.txjc.Util.ToastUtil;
import com.google.gson.Gson;
import com.zk.code.net.NetConfig;
import com.zk.code.net.UdpClient;

import org.xutils.common.Callback;
import org.xutils.http.RequestParams;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class TestNetActivity extends AppCompatActivity {

    @BindView(R.id.conn_btn)
    Button connBtn;
    @BindView(R.id.takephoto_btn)
    Button takephoto_btn;
    @BindView(R.id.takevideo_btn)
    Button takevideo_btn;
    @BindView(R.id.imagecon_btn)
    Button imagecon_btn;
    private Context context;
    private String content="";
    private String id;
    public static final int RECORD_SYSTEM_VIDEO = 100;
    //private  SerialPortUtils serialPortUtils;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_test_net);
        ButterKnife.bind(this);
        context=this;
        createTxt();
        if(isWiFiActive(TestNetActivity.this)){
            //  ToastUtil.show(TestNetActivity.this,"已连接网络");
        }else{
            //  ToastUtil.show(TestNetActivity.this,"已断开网络");
        }
        //请求拍照
        final Handler handler = new Handler();
        Runnable runnable = new Runnable() {
            @Override
            public void run() {
                try {
                    handler.postDelayed(this, 10*1000);
                    getStatus();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        };
        handler.postDelayed(runnable, 1000); // 在初始化方法里.

        //请求视频
        final Handler handler2 = new Handler();
        Runnable runnable2 = new Runnable() {
            @Override
            public void run() {
                try {
                    handler2.postDelayed(this, 10*1000);
                    getVideoStatus();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        };
        handler2.postDelayed(runnable2, 1000); // 在初始化方法里.

        //定时上传照片
        final Handler handler1 = new Handler();
        Runnable runnable1 = new Runnable() {
            @Override
            public void run() {
                try {
                    handler1.postDelayed(this, 15*60*1000);
                    startActivityForResult(new Intent(TestNetActivity.this, TakePhotoActivity.class).putExtra("CameraNo","0"),0);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        };
        handler1.postDelayed(runnable1, 15*60*1000); // 在初始化方法里.

     /*   final Handler handler3 = new Handler();
        Runnable runnable3 = new Runnable() {
            @Override
            public void run() {
                try {
                    handler3.postDelayed(this, 5*1000);
                    serialPortUtils = new SerialPortUtils();
                    serialPortUtils.openSerialPort();
                    serialPortUtils.sendSerialPort("running");
                    serialPortUtils.closeSerialPort();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        };
        handler3.postDelayed(runnable3, 5*1000); // 在初始化方法里.*/

    }

    /*@OnClick(R.id.conn_btn)
    public void onViewClicked() {
        UdpClient.sendMessage("你好 服务器 第一次发送");
    }
    @OnClick(R.id.takephoto_btn)
    public void onClicked() {

    }
    @OnClick(R.id.takevideo_btn)
    public void onVideobtn(){
       //startActivity(new Intent(TestNetActivity.this,TakeVideoActivity.class));
        startActivityForResult(new Intent(context,VideoActivity.class),RECORD_SYSTEM_VIDEO);
    }
    @OnClick(R.id.imagecon_btn)
    public void imagecon_btn(){
        startActivity(new Intent(TestNetActivity.this, ImagecontrastActivity.class));
    }*/

    //请求拍照  服务端
    public void getStatus(){
        RequestParams params = new RequestParams(ProjectConfig.SERVER_URL+"photorequest/getBystatus");
        params.addBodyParameter("ClientID",content);
        NetUtil.postData(params, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                Gson gson = new Gson();
                PhotoRequest photoRequest = gson.fromJson(result,PhotoRequest.class);
                id=String.valueOf(photoRequest.getId());
                SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//设置日期格式
                //  String date = df.format(new Date());
                String download = photoRequest.getDowloaddate();
                try {
                    Date date = df.parse(download);
                    int a = (int)((new Date().getTime()-date.getTime())/1000);
                    // ToastUtil.show(TestNetActivity.this,String.valueOf(a));
                    // Log.e("时间差别",String.valueOf(a));
                    if(a<120){
                        updateStatus(id,"photo");
                        startActivityForResult(new Intent(TestNetActivity.this, TakePhotoActivity.class).putExtra("CameraNo",photoRequest.getCamerano()),3);
                    }
                }catch(ParseException e){
                    e.printStackTrace();
                }
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {

            }

            @Override
            public void onCancelled(CancelledException cex) {

            }

            @Override
            public void onFinished() {

            }
        });
    }

    public void updateStatus(String id,String flag){
        String url="";
        if(flag.equals("photo")){
            url="/photorequest/updateStatus";
        }else{
            url="/videorequest/updateStatus";
        }
        RequestParams params = new RequestParams(ProjectConfig.SERVER_URL+url);
        params.addBodyParameter("id",id);
        NetUtil.postData(params, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {

            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {

            }

            @Override
            public void onCancelled(CancelledException cex) {

            }

            @Override
            public void onFinished() {

            }
        });
    }

    //请求拍视频  服务端
    public void getVideoStatus(){
        RequestParams params = new RequestParams(ProjectConfig.SERVER_URL+"videorequest/getBystatus");
        params.addBodyParameter("ClientID",content);
        NetUtil.postData(params, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                Gson gson = new Gson();
                PhotoRequest photoRequest = gson.fromJson(result,PhotoRequest.class);
                id=String.valueOf(photoRequest.getId());
                SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//设置日期格式
                //  String date = df.format(new Date());
                String download = photoRequest.getDowloaddate();
                try {
                    Date date = df.parse(download);
                    int a = (int)((new Date().getTime()-date.getTime())/1000);
                    // ToastUtil.show(TestNetActivity.this,String.valueOf(a));
                    // Log.e("时间差别",String.valueOf(a));
                    if(a<120){
                        updateStatus(id,"video");
                        startActivityForResult(new Intent(TestNetActivity.this, VideoActivity.class).putExtra("CameraNo",photoRequest.getCamerano()),RECORD_SYSTEM_VIDEO);
                    }
                }catch(ParseException e){
                    e.printStackTrace();
                }
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {

            }

            @Override
            public void onCancelled(CancelledException cex) {

            }

            @Override
            public void onFinished() {

            }
        });
    }

    public void createTxt() {
        String sdCardDir = Environment.getExternalStorageDirectory().getAbsolutePath();
        String FILE_NAME = "clintid.txt";
        File file = new File(sdCardDir, FILE_NAME);
        if (file.getName().endsWith(".txt")) {    //文件格式为txt文件
            try {
                InputStream instream = new FileInputStream(file);
                if (instream != null) {
                    InputStreamReader inputreader = new InputStreamReader(instream, "GBK");
                    BufferedReader buffreader = new BufferedReader(inputreader);
                    String line = "";
                    //分行读取
                    while ((line = buffreader.readLine()) != null) {
                        content += line ;
                    }
                    instream.close();        //关闭输入流
                }
            } catch (java.io.FileNotFoundException e) {

            } catch (IOException e) {

            }
        }
    }

    public static boolean isWiFiActive(Context inContext) {

        WifiManager mWifiManager = (WifiManager) inContext.getSystemService(Context.WIFI_SERVICE);
        WifiInfo wifiInfo = mWifiManager.getConnectionInfo();
        int ipAddress = wifiInfo == null ? 0 : wifiInfo.getIpAddress();
        if (mWifiManager.isWifiEnabled() && ipAddress != 0) {
            System.out.println("**** WIFI is on");
            return true;
        } else {
            System.out.println("**** WIFI is off");
            return false;
        }
    }
    public void uploadphoto(String photoUrl){
        RequestParams params = new RequestParams(ProjectConfig.SERVER_URL+"/photorequest/uploadphoto");
        params.addBodyParameter("PicName",new File(photoUrl));
        params.addBodyParameter("id",id);
        NetUtil.postData(params, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                if(result.equals("success")){
                    ToastUtil.show(context,"success");
                }
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {

            }

            @Override
            public void onCancelled(CancelledException cex) {

            }

            @Override
            public void onFinished() {

            }
        });
    }

    public void uploadVideo(String photoUrl){
        RequestParams params = new RequestParams(ProjectConfig.SERVER_URL+"/videorequest/uploadvideo");
        params.addBodyParameter("VideoName",new File(photoUrl));
        params.addBodyParameter("id",id);
        NetUtil.postData(params, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                if(result.equals("success")){
                    ToastUtil.show(context,"success");
                }
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {

            }

            @Override
            public void onCancelled(CancelledException cex) {

            }

            @Override
            public void onFinished() {

            }
        });
    }

    public void timeingupload(String photoUrl, final String cameraNo){
        RequestParams params = new RequestParams(ProjectConfig.SERVER_URL+"/picupload/save");
        params.addBodyParameter("ClientID",content);
        params.addBodyParameter("CameraNo",cameraNo);
        params.addBodyParameter("VideoName",new File(photoUrl));
        NetUtil.postData(params, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                if(cameraNo.equals("0")){
                    startActivityForResult(new Intent(TestNetActivity.this, TakePhotoActivity.class).putExtra("CameraNo","1"),1);
                }else{
                    return;
                }
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {

            }

            @Override
            public void onCancelled(CancelledException cex) {

            }

            @Override
            public void onFinished() {

            }
        });
    }
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        String photoUrl=data.getStringExtra("photoUrl");
        if (resultCode == RESULT_OK && requestCode==3) {
            uploadphoto(photoUrl);
        }else if(resultCode == RESULT_OK && requestCode==0){
            timeingupload(photoUrl,"0");
        }else if(resultCode == RESULT_OK && requestCode==1){
            timeingupload(photoUrl,"1");
        }else if(resultCode == RESULT_OK && requestCode==RECORD_SYSTEM_VIDEO){
            String videoPath=data.getStringExtra("path");
            uploadVideo(videoPath);
            ToastUtil.show(context,videoPath);
        }
        super.onActivityResult(requestCode, resultCode, data);
    }
}
